#include <stdio.h>
#include <pthread.h>

#include "census.h"
#include "censusslave.h"
#include "network.h"

int continueCensus;

void slaveCensusReceiveRequests()
{
	struct Socket socket;
	
	struct Packet answer;
	answer.size = sprintf(answer.buffer, CENSUS_ANSWER);
	
	if(0 == createSocketUDP(&socket, CENSUS_PORT))
	{
		if(0 == bindSocket(&socket))
		{
			struct Packet packet;
			struct Address address;
			
			while(continueCensus)
			{
				if(0 == receivePacket(&socket, &packet, &address))
				{
					if(isRequest(packet.buffer, packet.size))
					{
						printf("Census-Slave received request from ");
						printAddress(&address);
						printf("\n");
						
						if(0 == sendPacket(&socket, &answer, &address))
						{
							// Packet was sent
						}
					}
				}
			}
		}
	}
}

void startCensusSlave()
{
	continueCensus = 1;
	
	pthread_t threadReceiveRequests;
	pthread_create(&threadReceiveRequests, 0, (void *)&slaveCensusReceiveRequests, 0);
}

void stopCensusMaster()
{
	continueCensus = 0;
}
